<template>
	<view>
		<view class="p-4 flex flex-column grid-gap-4">
			<x-alert v-if="form.examine === 0" type="warning" bg>正在审核中，请耐心等待</x-alert>
			<x-alert v-if="form.message && form.examine === 3" type="danger-light-3">{{ form.message }}</x-alert>
			<view class="p-4 bg-white rounded-4 flex flex-column grid-gap-4">
				<view class="flex rounded-4 p-4 flex-center grid-gap-2" hover-class="bg">
					<text class="h9 text-grey">名称</text>
					<input type="text" class="flex-1 text-right font-weight-600 h9" placeholder="请输入名称"
						v-model="form.title" :disabled="formDisabled">
				</view>
				<view class="flex rounded-4 p-4 flex-center grid-gap-2" hover-class="bg">
					<text class="h9 text-grey">手机号码</text>
					<input type="tel" class="flex-1 text-right font-weight-600 h9" placeholder="请输入手机号码" maxlength="11"
						v-model="form.mobile" :disabled="formDisabled">
				</view>
				<view class="flex rounded-4 p-4 flex-center grid-gap-2" hover-class="bg">
					<text class="h9 text-grey">备注</text>
					<textarea class="flex-1 text-right font-weight-600 h9" auto-height maxlength="255"
						placeholder-class="text-placeholder" placeholder="在此输入备注信息" v-model="form.remark"
						:disabled="formDisabled"></textarea>
				</view>
				<view class="flex rounded-4 p-4 flex-center grid-gap-2" hover-class="bg" v-if="config.category"
					@tap="clickCategory">
					<text class="flex-1 h9 text-grey">入驻类目</text>
					<x-picker v-model:show="showCategory" v-model="form.category_id" :columns="[config.category]"
						confirm-color="var(--xl-primary)" @confirm="categoryConfirm">
						<text class="h9 font-weight-600" v-if="form.category_id"> {{ form.category }} </text>
						<text class="h9 font-weight-600 text-placeholder" v-else> 请选择入驻类目</text>
					</x-picker>
				</view>
				<view class="flex rounded-4 p-4 flex-center grid-gap-2" hover-class="bg" @tap="chooseLocation" v-if="showSelectMap">
					<view class="w-100px text-primary h9 font-weight-600">在地图上选择</view>
					<view class="flex-1"></view>
					<uni-icons type="location-filled" size="20" color="var(--xl-primary)"></uni-icons>
				</view>
				<view class="flex rounded-4 p-4 flex-center grid-gap-2" hover-class="bg" @tap="!formDisabled && $refs.xRegionsRef.show()">
					<text class="h9 text-grey text-nowrap">选择地区</text>
					<view class="flex-1 flex flex-x-flex-end">
						<text v-if="form.province_id" class="font-weight-600 h9 text-break-all text-wrap">{{
							form.province }} {{ form.city }} {{ form.area }} {{ form.street }}</text>
						<text class="text-placeholder font-weight-600 h9" v-else> 请选择地区 </text>
					</view>
					<uni-icons type="right" color="var(--xl-placeholder)"></uni-icons>
				</view>
				<view class="flex rounded-4 p-4 flex-center grid-gap-2" hover-class="bg">
					<text class="h9 text-grey">详细地址</text>
					<textarea class="flex-1 text-right font-weight-600 h9" auto-height maxlength="200"
						placeholder-class="text-placeholder" placeholder="详细地址，例如：XX小区X栋X单元X楼8888号" v-model="form.address_detail"
						:disabled="formDisabled"></textarea>
				</view>
			</view>

			<view class="flex">
				<template v-if="form.examine == 0">
					<button class="flex-1 btn-dark-light-3 btn-round" disabled>审核中</button>
				</template>
				<template v-if="form.examine === null || form.examine == 3">
					<button class="flex-1 btn-primary btn-round" @click="submit()">提交</button>
				</template>
				<template v-if="form.examine == 1">
					<button class="flex-1 btn-success btn-round" @tap="$page.redirect('/channels/pages/index/index')">渠道商中心</button>
				</template>
			</view>
			<text class="h9 text-placeholder">{{ config.channels_apply_tips }}</text>
		</view>

		<!-- 选择意向城市 -->
		<x-regions ref="xRegionsRef" @selected="selectedRegions" />
		<x-login ref="xLoginRef" @success="getInfo()" />
		<x-loading v-if="loading" />
	</view>
</template>

<script setup lang="ts">
import { ref, computed,watchEffect } from 'vue';
import { login, $api, $message, $auth, $page } from '@/utils';
import { onLoad,onUnload } from '@dcloudio/uni-app';
import { useUserStore,useWebConfigStore, useRefs } from "@/stores";
import { $EventName } from '@/utils/const/env';
const UserStore = useUserStore();
const WebConfigStore = useWebConfigStore();
const { WEBCONFIG } = useRefs(WebConfigStore);
const showSelectMap = ref(true);
// #ifdef H5 || MP-WEIXIN
watchEffect(() => {
	// #ifdef H5
	showSelectMap.value = WEBCONFIG.value?.amap_web_key ? true : false;
	// #endif
	// #ifdef MP-WEIXIN
	showSelectMap.value = WEBCONFIG.value?.amap_mini_key ? true : false;
	// #endif
})
// #endif
const form = ref({
	id: '',
	title: '',
	remark: '',
	mobile: '',
	category_id: '',
	category: '',
	province_id: "",
	province: '',
	city_id: "",
	city: '',
	area_id: "",
	area: '',
	street_id: "",
	street: '',
	address_detail: '',
	latitude: 0,
	longitude: 0,
	examine: null,
	message: "",
});
const config = ref({
	channels_apply_tips: '',
	category: [],
});
const showCategory = ref(false);
const loading = ref(false);
const formDisabled = computed(() => {
	return form.value.examine === 1 || form.value.examine === 0;
});
const xLoginRef = ref();
const xRegionsRef = ref();
const getInfo = () => {
	if (!UserStore.hasLogin()) return;
	$api.Channels.info().then((data: any) => {
		form.value = data;
	}).catch(() => {
	})
}
const submit = () => {
	if (!UserStore.hasLogin()) {
		return login({
			redirect: 'channels/pages/user/apply',
			params:{
				id:form.value.id
			}
		}, xLoginRef.value);
	}
	if(!form.value.latitude||!form.value.longitude){
		uni.showModal({
			content: '还未在地图上选择地址，是否立即选择',
			success: (res:any) => {
				if (res.confirm) {
					chooseLocation();
				}
			}
		})
		return;
	}
	if(loading.value) return;
	loading.value = true;
	$api.Channels.apply(form.value).then((res: any) => {
		$message.success(res.msg);
		getInfo();
	}).catch((err: any) => {
		$message.error(err.msg);
	}).finally(() => {
		loading.value = false;
	})
}
const selectedRegions = (regions: any) => {
	if (regions.province_id) {
		form.value.province_id = regions.province_id;
		form.value.province = regions.province;
	} else {
		form.value.province_id = '';
		form.value.province = '';
	}
	if (regions.city_id) {
		form.value.city_id = regions.city_id;
		form.value.city = regions.city;
	} else {
		form.value.city_id = '';
		form.value.city = '';
	}
	if (regions.area_id) {
		form.value.area_id = regions.area_id;
		form.value.area = regions.area;
	} else {
		form.value.area_id = '';
		form.value.area = '';
	}
	if (regions.street_id) {
		form.value.street_id = regions.street_id;
		form.value.street = regions.street;
	} else {
		form.value.street_id = '';
		form.value.street = '';
	}
}

const EventNameCHOOSE_LOCATION = `ChannelsAddressChooseLocation${$EventName.CHOOSE_LOCATION}`;
const chooseLocation = () => {
	uni.chooseLocation({
		success: (res: any) => {
			form.value.address_detail = res.address;
			updateLocation(res);
		}
	})
}
const updateLocation = (res: any) => {
	form.value.latitude = res.latitude;
	form.value.longitude = res.longitude;
	loading.value = true;
	$api.Map.regeo({
		lnglat: [res.longitude, res.latitude]
	}).then((res: any) => {
		let data = res.data;
		const formattedAddress = data.formatted_address;
		const addressComponent = data.addressComponent;
		data.desc = formattedAddress
			.replace(addressComponent.province + addressComponent.city + addressComponent.district + addressComponent.township, '');
		form.value.address_detail = data.desc;
		xRegionsRef.value.search({
			province:addressComponent.province,
			city:addressComponent.city||addressComponent.province,
			area:addressComponent.district,
			street:addressComponent.township
		})
	}).catch((err: any) => {
		$message.error(err.msg);
	}).finally(() => {
		loading.value = false;
	})
}

const getConfig = () => {
	$api.Config.channels().then((res: any) => {
		config.value = res;
	}).catch(() => {
	})
}
const clickCategory = () => {
	if (formDisabled.value) return;
	showCategory.value = true;
}
const categoryConfirm = (val: any) => {
	form.value.category = val.label;
}
onLoad((options: any) => {
	if(options.id){
		form.value.id = options.id;
	}
	getInfo();
	getConfig();
	uni.$on(EventNameCHOOSE_LOCATION, updateLocation)
})
onUnload(() => {
	uni.$off(EventNameCHOOSE_LOCATION, updateLocation)
});
</script>
